package eerbaar.shared.persist.internal.lib;

import java.util.ArrayList;
import java.util.List;

import eerbaar.level.IState;
import eerbaar.level.IStates;
import eerbaar.level.LevelFactory;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class StatesPersister implements IPersister<IStates> {

    public static final String NAME = "states";

    private IStates target;

    public StatesPersister() {
        //
    }

    public StatesPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    public StatesPersister(IStates wrapper) {
        this.target = wrapper;
    }

    @Override
    public Class<IStates> getRegistertedInterface() {
        return IStates.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        List<StatePersister> result = new ArrayList<StatePersister>();

        IState[] states = this.target.getStates();
        for (IState e : states) {
            StatePersister p = new StatePersister(e);
            result.add(p);
        }

        return result.toArray(new StatePersister[] {});
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IStates getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IStates load(INode node) {
        assert (node != null);

        IStates result = LevelFactory.createStates();

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        List<INode> list = NodeCmdFactory.findChildren(node,
                StatePersister.NAME);
        for (INode n : list) {
            try {
                IState state = service.load(IState.class, n);
                result.addState(state);
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IStates obj) {
        this.target = obj;
    }

}
